<template>
  <el-dialog
    v-el-drag-dialog="{updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :width="setDialogWidth('1000px')"
    :visible="visible"
    :title="title"
    @open="open"
    @close="close"
  >
    <el-form
      ref="form"
      class="flex flex-wrap"
      label-width="auto"
      :model="form"
      :rules="rules"
    >
      <el-form-item :label="$t('USER_NUM')" prop="userId" class="w-50">
        <el-input
          v-model.trim="form.userId"
          maxlength="32"
          :readonly="type != 'add'"
          :placeholder="$t('ENTER_USER_NUMBER')"
        />
      </el-form-item>
      <el-form-item :label="$t('ROLE')" prop="roleId" class="w-50">
        <el-select
          v-model="form.roleId"
          :placeholder="$t('SELECT_ROLE')"
          :disabled="type == 'view' || data.userId === 'admin' "
          clearable
        >
          <el-option
            v-for="item in roleList"
            :key="item.roleId"
            :label="item.roleName"
            :value="item.roleId"
            :disabled="selectAuth(item.roleId)"
          />
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('AFFILIATION')" prop="orgId" class="w-50">
        <el-select
          ref="orgSelect"
          v-model="form.orgId"
          :disabled="type == 'view' || data.userId === 'admin'"
          popper-class="select-tree"
          :placeholder="$t('PLEASE_SELECT_ORG')"
        >
          <el-option
            class="tree-option"
            :value="form.orgId"
            :label="$findName(form.orgId, orgTree, 'orgId', 'orgName')"
          >
            <el-tree
              :key="renderKey"
              :data="orgTree"
              accordion
              @node-click="nodeClick"
            />
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="$t('REAL_NAME')" prop="realName" class="w-50">
        <el-input
          v-model.trim="form.realName"
          maxlength="32"
          :readonly="type == 'view'"
          :placeholder="$t('ENTER_REAL_NAME')"
        />
      </el-form-item>
      <el-form-item :label="$t('MOBILE')" prop="phone" class="w-50">
        <el-input
          v-model="form.phone"
          maxlength="16"
          :readonly="type == 'view'"
          :placeholder="$t('PLEASE_ENTER_PHONE')"
        />
      </el-form-item>
      <el-form-item :label="$t('DATEOFBIRTH')" prop="birthday" class="w-50">
        <el-date-picker
          v-model="form.birthday"
          type="date"
          :editable="false"
          value-format="yyyy-MM-dd"
          :picker-options="birthdayPickerOptions"
          :readonly="type === 'view'"
          :placeholder="$t('PLEASE_SELECT_BIRTH')"
        />
      </el-form-item>
      <el-form-item :label="$t('EMAIL')" prop="email" class="w-50">
        <el-input
          v-model="form.email"
          maxlength="128"
          :readonly="type == 'view'"
          :placeholder="$t('PLEASE_ENTER_EMAIL')"
        />
      </el-form-item>
      <el-form-item :label="$t('CONTACTADDRESS')" prop="address" class="w-50">
        <el-input
          v-model="form.address"
          maxlength="256"
          :readonly="type == 'view'"
          :placeholder="$t('PLEASE_ENTER_CONTACT_ADDRESS')"
        />
      </el-form-item>
      <el-form-item :label="$t('GENDER')" prop="gender" class="w-50">
        <el-radio-group
          v-model="form.gender"
          :disabled="type == 'view'"
          size="mini"
        >
          <el-radio-button :label="$t('MALE')" />
          <el-radio-button :label="$t('WOMAN')" />
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="$t('WHETHER_ENABLE')" prop="enable" class="w-50">
        <el-radio-group
          v-model="form.enable"
          :disabled="type == 'view' || data.userId === 'admin'"
          size="mini"
        >
          <el-radio-button label="true">{{ $t('ENABLE') }}</el-radio-button>
          <el-radio-button label="false">{{ $t('DISABLE') }}</el-radio-button>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <template v-if="type == 'view'">
        <el-button @click="close">{{ $t('CLOSE') }}</el-button>
      </template>
      <template v-else>
        <el-button @click="close">{{ $t('CANCEL') }}</el-button>
        <el-button type="primary" @click="$debounce(save)">{{
          $t('SAVE')
        }}</el-button>
      </template>
    </template>
  </el-dialog>
</template>

<script>
  import { mapGetters } from 'vuex'
  import UserApi from '@/api/system/UserApi'

  export default {
    props: {
      visible: Boolean,
      type: { type: String, default: '' },
      data: { type: Object, default: () => {} },
      orgTree: { type: Array, default: () => [] },
      baseRoleList: { type: Array, default: () => [] }
    },
    data() {
      return {
        form: {},
        renderKey: 0,
        birthdayPickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now()
          }
        }
      }
    },
    computed: {
      ...mapGetters(['getOrg', 'getRoles']),
      title() {
        if (this.type === 'add') {
          return this.$t('NEWUSERS') // '新增用户'
        } else if (this.type === 'view') {
          return this.$t('TOVIEWTHEUSER') // '查看用户'
        }
        return this.$t('MODIFYTHEUSER') // '修改用户'
      },
      rules() {
        return {
          userId: [
            {
              required: true,
              message: this.$t('USER_NUMBER_NOT_EMPTY'), // '用户编号不能为空',
              trigger: 'blur'
            },
            {
              pattern: /^[a-zA-Z0-9_]+$/,
              message: this.$t('ONLY_ENGLISH_NUMBER'), // '只能为英文、数字、下划线',
              trigger: 'blur'
            }
          ],
          realName: [
            {
              required: true,
              message: this.$t('REAL_NAME_NOT_EMPTY'), // '真实姓名不能为空',
              trigger: 'blur'
            }
          ],
          orgId: [
            {
              required: true,
              message: this.$t('ORG_NOT_EMPTY'), // '所属机构不能为空',
              trigger: 'blur'
            }
          ],
          roleId: [
            {
              required: true,
              message: this.$t('ROLE_NOT_EMPTY'), // '所属角色不能为空',
              trigger: 'blur'
            }
          ],
          phone: [
            {
              pattern: /^\d{6,12}$/,
              message: this.$t('PHONE_NUMBER_FORMAT_INCORRECT'), // '电话号码格式错误',
              trigger: 'blur'
            }
          ],
          email: [
            {
              type: 'email',
              message: this.$t('EMAIL_FORMAT_WRONG'), // '电子邮箱格式错误',
              trigger: 'blur'
            }
          ]
        }
      },
      roleList() {
        if (this.type === 'view') {
          return this.baseRoleList
        } else {
          return this.baseRoleList.filter(i => i.roleId !== 'admin')
        }
      }
    },
    created() {
    },
    methods: {
      selectAuth(roleId) {
        let disabled = false
        const currentRole = window.__config__.roleLevel.find(i => i.id === this.getRoles[0]) || ''
        const currentRowRole = window.__config__.roleLevel.find(i => i.id === roleId) || ''
        if (currentRowRole) {
          if (currentRole.level <= currentRowRole.level) {
            disabled = false
          } else {
            disabled = true
          }
        }
        return disabled
      },
      defaultData() {
        return {
          userId: '',
          realName: '',
          orgId: null,
          roleId: null,
          phone: '',
          birthday: '',
          email: '',
          gender: '男',
          address: '',
          enable: true
        }
      },
      open() {
        this.renderKey += 1
        this.$refs.form && this.$refs.form.clearValidate()
        this.form = Object.assign(this.defaultData(), this.data)
      },
      nodeClick(node) {
        this.form.orgId = node.orgId
        this.form.orgName = node.orgName
        this.$refs.orgSelect.blur()
      },
      save() {
        this.$refs.form.validate(valid => {
          if (!valid) {
            return false
          }
          UserApi[this.type]({
            ...this.form,
            orgName: this.form.orgId ? this.$findName(this.form.orgId, this.orgTree, 'orgId', 'orgName') : '',
            roleName: this.form.roleId ? this.$findName(this.form.roleId, this.roleList, 'roleId', 'roleName') : ''
          }).then(result => {
            if (result) {
              this.$message.success(this.$t('SAVE_SUCCESS'))
              this.close(true)
            }
          })
        })
      },
      close(load) {
        this.$emit('close', load)
      }
    }
  }
</script>

<style scoped></style>
